package {
import flash.display.Sprite;
import flash.utils.getTimer;
import flash.utils.FastMath;
import flash.text.TextField;
import flash.system.Capabilities;
	public class Test extends Sprite
	{
		private static const NUM_OPS:int = 2048;
		public function Test() {
			var vec1:Vector.<Number> = new Vector.<Number>(NUM_OPS, true);
			var vec2:Vector.<Number> = new Vector.<Number>(NUM_OPS, true);
			var i:int, j:int;
			var t1:int, t2:int;
			var fastmathT:int, mathT:int;
			var tf:TextField = new TextField();
			var err:Number = 0;
			addChild(tf);
			tf.width = 400;
			tf.height = 400;
			tf.multiline = true;
			tf.text = Capabilities.os + " " + Capabilities.playerType + " " + Capabilities.version;
			if (Capabilities.isDebugger) tf.appendText(" DEBUGGER");
			tf.appendText("\n\n");
			fastmathT = 0; mathT = 0;
			for (j = 0; j < NUM_OPS; ++ j) {
				for (i = 0; i < NUM_OPS; ++ i)
					vec1[i] = vec2[i] += Math.random();
				t1 = getTimer();
				FastMath.sqrt(vec2);
				t2 = getTimer();
				fastmathT += t2 - t1;
				for(i = 0; i < NUM_OPS; ++ i) vec1[i] = Math.sqrt(vec1[i]);
				t1 = getTimer();
				mathT += t1 - t2;
			}

			tf.appendText("Math.sqrt: " + Math.round(NUM_OPS*NUM_OPS / mathT) + " op/ms\n" +
			              "FastMath.sqrt: " + Math.round(NUM_OPS*NUM_OPS / fastmathT) + " op/ms\n");
			err = 0;
			for (i = 0; i < NUM_OPS; ++ i) {
				err += Math.abs(vec2[i] - vec1[i]) / vec1[i];
			}
			tf.appendText("FastMath is " + Math.round(100 * mathT / fastmathT)/100 + "x faster (with vectors of " + NUM_OPS + " items)\n");
			tf.appendText("Average error: " + Math.round(err * 10000. / NUM_OPS)/100 + "%\n\n");

			
			fastmathT = 0; mathT = 0;
			for (j = 0; j < NUM_OPS; ++ j) {
				for (i = 0; i < NUM_OPS; ++ i)
					vec1[i] = vec2[i] += Math.random();
				t1 = getTimer();
				FastMath.invSqrt(vec2);
				t2 = getTimer();
				fastmathT += t2 - t1;
				for(i = 0; i < NUM_OPS; ++ i) vec1[i] = 1. / Math.sqrt(vec1[i]);
				t1 = getTimer();
				mathT += t1 - t2;
			}

			tf.appendText("1. / Math.sqrt: " + Math.round(NUM_OPS*NUM_OPS / mathT) + " op/ms\n" +
			              "FastMath.invSqrt: " + Math.round(NUM_OPS*NUM_OPS / fastmathT) + " op/ms\n");
			err = 0;
			for (i = 0; i < NUM_OPS; ++ i) {
				err += Math.abs(vec2[i] - vec1[i]) / vec1[i];
			}
			tf.appendText("FastMath is " + Math.round(100 * mathT / fastmathT)/100 + "x faster (with vectors of " + NUM_OPS + " items)\n");
			tf.appendText("Average error: " + Math.round(err * 10000. / NUM_OPS)/100 + "%\n\n");
		}
	}
}
